package com.itmg.search.business.service.impl;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.itmg.cache.sort.SortByModelCount;
import com.itmg.search.business.bean.SearchBean;
import com.itmg.search.business.service.SearchService;
import com.itmg.search.form.SearchForm;
import com.itmg.search.web.DataItemView;
import com.itmg.search.web.ResultView;
import com.itmg.taskmanager.ISearchDataManager;
import com.itmg.taskmanager.impl.SearchManagerImpl;
import com.itmg.tools.bean.PriceBean;
import com.itmg.tools.page.PageBean;
import com.itmg.util.Constants;
import com.itmg.vo.ModelCount;
import com.itmg.vo.PriceView;
import com.itmg.vo.SearchParameterVO;
import com.itmg.vo.SearchResultItemVO;
import com.itmg.vo.SearchResultVO;

/**
 * 搜索业务类
 *
 */
public class SearchServiceImpl implements SearchService {
	
	private ISearchDataManager searchDataManager = new SearchManagerImpl();
	
	public SearchServiceImpl() {
	}
    
	@SuppressWarnings("unchecked")
	public ResultView getResultView(SearchForm searchForm,PageBean page,HttpServletRequest request) throws Exception {
		
		ResultView resultView = new ResultView();
		SearchParameterVO searchParameterVO = new SearchParameterVO();
		String keywords = searchForm.getKeywords();
		searchForm.setKeywords(keywords);
		searchParameterVO.setKeyword(keywords);
		searchParameterVO.setCategory(searchForm.getCategory());
		searchParameterVO.setMinPrice(searchForm.getMinPrice());
		searchParameterVO.setMaxPrice(searchForm.getMaxPrice());
		searchParameterVO.setSort(searchForm.getSort());
		searchParameterVO.setIsAuction(searchForm.getIsAuction());
		searchParameterVO.setPage(page);
		
		SearchResultVO searchResultVO = searchDataManager.getSearchResult(searchParameterVO,request);
		
		//价格区间的格式化
		DecimalFormat df = new DecimalFormat("#,##0");
		List<PriceBean> priceList = searchResultVO.getPriceList();
		if(priceList != null){
			List<PriceView> PriceViewList = new ArrayList<PriceView>();
			for(PriceBean bean:priceList){
				PriceView view = new PriceView();
				view.setMaxPrice(bean.getMaxPrice());
				view.setMinPrice(bean.getMinPrice());
				if(bean.getMaxPrice() != null)
					view.setMaxPrice_str(df.format(bean.getMaxPrice()));
				if(bean.getMinPrice() != null)
					view.setMinPrice_str(df.format(bean.getMinPrice()));
				PriceViewList.add(view);
			}
			resultView.setPriceList(PriceViewList);
		}
		
		//对所有的型号出现次数进行排序
		List<ModelCount> modelList = searchResultVO.getModelList();
		if(modelList != null){
			Collections.sort(modelList, new SortByModelCount());
			List<String> viewList = new ArrayList<String>();
			int count = 0;
			for(ModelCount model:modelList){
				if(count < 30){
					if(model.getModel() != null && model.getModel().contains(Constants.REGEX_XIE)){
						String[] models = model.getModel().split(Constants.REGEX_XIE);
						for(String m : models){
							if(m.length()>2 && !m.matches(Constants.REGEX_NUMBER) && !viewList.contains(m)){
								viewList.add(m);
								count++;
							}
						}
					}else{
						viewList.add(model.getModel());
						count++;
					}
				}else
					break;
			}
			resultView.setModelList(viewList);
		}
//		List<String> brandList = searchResultVO.getBrandList();
//		if(brandList != null){
//			List<BrandView> viewList = new ArrayList<BrandView>();
//			for(String brand : brandList){
//				BrandView view = new BrandView();
//				view.setView(brand);
//				view.setAlias(brand.replaceAll("/", " "));
//				viewList.add(view);
//			}
//			resultView.setBrandList(viewList);
//		}
		
		List<SearchResultItemVO> resultItemList = searchResultVO.getResultItemList();
		List<DataItemView> dataItemViewList = null;
		if(resultItemList != null)
		{
			dataItemViewList = SearchBean.getDataItemViewList(resultItemList);
		}
		if(dataItemViewList.size() == 0)
			resultView.setFlag(1);
		resultView.setPage(page);
		resultView.setDataItemViewList(dataItemViewList);
		resultView.setBegin_num(String.valueOf(page.getBegin()));
		
		java.text.DecimalFormat format = new java.text.DecimalFormat("#,##0");
    	String total_number = format.format(page.getTotal());
		resultView.setData_total_num(total_number);
		resultView.setEnd_num(String.valueOf(page.getEnd()));
		
		String site_total_num = format.format(searchResultVO.getTotalResultNumber());
		resultView.setSite_total_num(site_total_num);
		
		resultView.setCondition_text(SearchBean.getCondition_text(searchForm));
		resultView.setKeywords(URLEncoder.encode(keywords,Constants.ENCODING_UTF8));
		resultView.setKeyword(keywords);
		
		resultView.setIsAuction(searchForm.getIsAuction());
		resultView.setSort(searchForm.getSort());
		return resultView;
	}
	
	/**
	 * @param SearchForm  action对应的bean
	 * @param request request请求
	 * @param response response相应
	 * @return 结束转向URL
	 */
	public String getStaticURL(SearchForm searchForm,HttpServletRequest request) throws Exception {
		
		//判断是否从result过来的请求		String type = searchForm.getType();
		String keywords = request.getParameter(Constants.VARIABLE_KEYWORDS);
        String category = request.getParameter(Constants.VARIABLE_CATEGORY);
        String sort = request.getParameter(Constants.VARIABLE_SORT);
        String isAuction = request.getParameter(Constants.VARIABLE_ISAUCTION);
		String max_str = request.getParameter(Constants.VARIABLE_MAX_PRICE);
		String min_str = request.getParameter(Constants.VARIABLE_MIN_PRICE);
		if(Constants.RESULT.equals(type) && Constants.ISAUCTION_DEFAULT.equals(sort)){
               max_str = null;
               min_str = null;
		}
		
		//参数多值的转化开始
        Integer minPrice = null;
        Integer maxPrice = null;
        if(max_str != null && !"".equals(max_str))
        	minPrice = Integer.parseInt(min_str);
        if(min_str != null && !"".equals(min_str))
        	maxPrice = Integer.parseInt(max_str);
        
        searchForm.setKeywords(keywords);
        searchForm.setCategory(category);
        searchForm.setSort(sort);
        searchForm.setMinPrice(minPrice);
        searchForm.setMaxPrice(maxPrice);
        searchForm.setIsAuction(isAuction);
        if(category != null && (Constants.DEFAULT_CATEGORY.equals(category) || Constants.DEFAULT_CATEGORY_1.equals(category))){
        	category = null;
        }
        
		// 参数多值的转化结束
        String flag = request.getParameter(Constants.FLAG_PATERMTER);
        //生成静态URL
		String url = "";
		String contextPath = request.getContextPath();
        if(flag != null && Constants.FLAG_DEFAULT.equals(flag)){
        	if(Constants.SORT_RELATIVE.equals(sort)){
        		if(isAuction != null && !Constants.ISAUCTION_DEFAULT.equals(isAuction)){
        			if(category != null && !"".equals(category)){
    					if(minPrice != null || maxPrice != null){
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    					          "/category/"+URLEncoder.encode(category, "UTF-8")+
    					          "/price/"+minPrice+"-"+maxPrice+
    					          "/"+"1/"+sort+"/"+isAuction;
    					}else{
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    					          "/category/"+URLEncoder.encode(category, "UTF-8")+
    					          "/"+"1/"+sort+"/"+isAuction;
    					}
    					
    				}else{
    					if(minPrice != null || maxPrice != null){
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    							  "/price/"+minPrice+"-"+maxPrice+
    							  "/"+"1/"+sort+"/"+isAuction;
    					}else{
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    						"/"+"1/"+sort+"/"+isAuction;
    					}
    				}
        		}else{
        			if(category != null && !"".equals(category)){
    					if(minPrice != null || maxPrice != null){
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    					          "/category/"+URLEncoder.encode(category, "UTF-8")+
    					          "/price/"+minPrice+"-"+maxPrice+"/";
    					}else{
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    					          "/category/"+URLEncoder.encode(category, "UTF-8")+"/";
    					}
    					
    				}else{
    					if(minPrice != null || maxPrice != null){
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
    							  "/price/"+minPrice+"-"+maxPrice+"/";
    					}else{
    						url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+"/";
    					}
    				}
        		}
        	}
        	else{
				if(category != null && !"".equals(category)){
					if(minPrice != null || maxPrice != null){
						if(isAuction != null && !"".equals(isAuction))
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
							      "/category/"+URLEncoder.encode(category, "UTF-8")+
							      "/price/"+minPrice+"-"+maxPrice+
						          "/"+"1/"+sort+"/"+isAuction;
						else
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
						          "/category/"+URLEncoder.encode(category, "UTF-8")+
						          "/price/"+minPrice+"-"+maxPrice+
					              "/"+"1/"+sort;
					}else{
						if(isAuction != null && !"".equals(isAuction))
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
							      "/category/"+URLEncoder.encode(category, "UTF-8")+
						          "/"+"1/"+sort+"/"+isAuction;
						else
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
						          "/category/"+URLEncoder.encode(category, "UTF-8")+
					              "/"+"1/"+sort;
					}
				}else{
					if(minPrice != null || maxPrice != null){
						if(isAuction != null || isAuction != null)
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
							      "/price/"+minPrice+"-"+maxPrice+
					              "/"+"1/"+sort+"/"+isAuction;
						else
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
							      "/price/"+minPrice+"-"+maxPrice+
					              "/"+"1/"+sort;
					}else{
						if(isAuction != null || isAuction != null)
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
					              "/"+"1/"+sort+"/"+isAuction;
						else
							url = contextPath+"/word/"+URLEncoder.encode(keywords, "UTF-8")+
					              "/"+"1/"+sort;
					}
				}
			}
			searchForm.setFlag(Constants.FLAG_1);
        }
		return url;
	}

}
